package io.zhengsh.juc;

/**
 * ‐XX:+UnlockDiagnosticVMOptions ‐XX:+PrintAssembly ‐Xcomp
 */
public class VisibilityTest {

    private boolean flag = true;
    private int count = 0;

    public void refresh() {
        flag = false;
        System.out.println(Thread.currentThread().getName() + "修改flag");
    }

    public void load() {
        System.out.println(Thread.currentThread().getName() + "开始执行.....");
        while (flag) {
            count++;
            //TODO 业务逻辑

            //1.写屏障
            //UnsafeFactory.getUnsafe().storeFence();

            //2.CPU 时间片切换, 线程上下文切换
            //Thread.yield();

            //3.打印 count
            //System.out.println(count);

            //4.等待，唤醒
            //shortWait(100);

            //5.对 count 加 volatile 描述符

            //6. sleep
            //Thread.sleep(500);

            //7. 设置为 Integer
            // 使用的是 final

            long start = System.nanoTime();
            long end = 0;
//            do {
//                end = System.nanoTime();
//            } while (start + 10000 >= end);
            while (start + 10000 >= end) {
                end = System.nanoTime();
            }
        }
        System.out.println(Thread.currentThread().getName() + "跳出循环: count=" + count);
    }

    public static void main(String[] args) throws InterruptedException {
        VisibilityTest test = new VisibilityTest();

        // 线程threadA模拟数据加载场景
        Thread threadA = new Thread(() -> test.load(), "threadA");
        threadA.start();

        // 让threadA执行一会儿
        Thread.sleep(1000);
        // 线程threadB通过flag控制threadA的执行时间
        Thread threadB = new Thread(() -> test.refresh(), "threadB");
        threadB.start();

    }


    public static void shortWait(long interval) {
        long start = System.nanoTime();
        long end;
        do {
            end = System.nanoTime();
        } while (start + interval >= end);
    }
}